package com.spica.platform.websocket.util;

import com.spica.platform.common.constant.CommonConstant;
import com.spica.platform.redis.repository.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 对用户相关统计操作
 * 引入redis，将当前连接人数存入redis中
 */
@Component
@Scope("singleton")
@Slf4j
public class SocketSessionRegistry {
    private final Object lock = new Object();
    @Autowired
    private RedisRepository redisRepository;

    //统计当前登录用户，保持了多少个通道session
    public Set<String> getSesss(String userId) {
        String webSocketKey = CommonConstant.WEBSOCKET_PREFIX + userId;
        return (Set)redisRepository.get(webSocketKey);
    }

    //查询所有连接
//    public ConcurrentHashMap<String, Set<String>> getAllSessionIds() {
//        return redisRepository.
//    }

    public void registerSessionId(String userId, String sessionId) {
        Assert.notNull(userId, "User ID must not be null");
        Assert.notNull(sessionId, "Session ID must not be null");
        String webSocketKey = CommonConstant.WEBSOCKET_PREFIX + userId;
        synchronized (this.lock) {
            Object set = this.getSesss(webSocketKey);
            if (set == null) {
                set = new CopyOnWriteArraySet();
            }
            ((Set) set).add(sessionId);

            log.info("===============当前在线人数=============:   " + ((Set) set).size());
            redisRepository.set(webSocketKey, set);
        }
    }

    public void unregisterSessionId(String userId, String sessionId) {
        Assert.notNull(userId, "User ID must not be null");
        Assert.notNull(sessionId, "Session ID must not be null");
        String webSocketKey = CommonConstant.WEBSOCKET_PREFIX + userId;
        synchronized (this.lock) {
            Set set = this.getSesss(webSocketKey);
            if (null == set) {
                return;
            }
            if (set.remove(sessionId) && set.isEmpty()) {
                redisRepository.del(webSocketKey);
            }
            if (set.remove(sessionId)) {
                redisRepository.set(webSocketKey, set);
            }
        }
    }
}
